class User < TwitterAuth::GenericUser
  # Extend and define your user model as you see fit.
  # All of the authentication logic is handled by the 
  # parent TwitterAuth::GenericUser class.
  
  def friends
    friends = Friend.find_all_by_user_id(self.twitter_id)
    hash = Hash.new
    friends.each{|f| hash[f.friend_id]=f} unless friends.nil?
    if friends.nil? or self.friends_requires_refresh?
      twitter_friends = self.twitter.get('/statuses/friends')
      twitter_friends.each do |f|
        begin
          hash.delete(f['id']) unless friends.nil?
          Friend.find_by_user_id_and_friend_id(self.twitter_id, f['id']).save 
        rescue 
          Friend.create(:user_id => self.twitter_id, :friend_id => f['id'])
        end
        friend = TwitterUser.find_by_twitter_id f['id']
        if friend.nil?
          f['twitter_id']=f['id']
          f.delete('status')
          friend = TwitterUser.create!(f)
        end
      end
      # anything remaining in hash should be deleted
      hash.each do |h|
        # would like this to be paranoid ...
        Friend.find_by_user_id_and_friend_id(self.twitter_id, h.friend_id).destroy
      end
      friends = Friend.find_all_by_user_id(self.twitter_id)
    end
    friends
  end
  # my twitter_id 11266912
  def friends_requires_refresh?
    friend = Friend.find(:first, :conditions => ["user_id = ?",self.twitter_id], :order=>'updated_at DESC')
    friend.updated_at < Time.now - 1.hour rescue true
  end
  # catch  TwitterAuth::Dispatcher::Error
  def friend_statuses(user_id)
    statuses = Status.find_all_by_user_id(user_id)
    begin
      if statuses.nil? or self.statuses_requires_refresh?(user_id)
        twitter_statuses = self.twitter.get("/statuses/user_timeline.json?id=#{user_id}")
        twitter_statuses.each do |s|
          begin
            Status.find_by_twitter_id(s['id']).save 
          rescue 
            s['twitter_id']=s['id']
            s['user_id'] = user_id
            s['twitter_created_at'] = s['created_at']
            s.delete('created_at')
            s.delete('user')
            Status.create(s)
          end
        end
        statuses = Status.find_all_by_user_id(user_id)
      end
    rescue Exception => exc
      # can't grab any more data at present ...
      logger.error("#{exc.class.inspect}: #{exc.message}")
    end
    statuses  
  end
  
  def statuses_requires_refresh?(user_id)
    status = Status.find(:first, :conditions => ["user_id = ?",user_id], :order=>'updated_at DESC')
    status.updated_at < Time.now - 1.hour rescue true
  end
end
